package site.beanyon.now.handler;

import com.mysql.cj.jdbc.exceptions.MysqlDataTruncation;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import site.beanyon.now.constant.ResponseEnum;
import site.beanyon.now.model.dto.HttpResponse;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 数据库SQL异常处理类
 */
@ControllerAdvice
public class SQLExceptionHandler {
    /**
     * 违反唯一约束的异常处理器
     *
     * @param e 异常实例对象
     * @return http响应结果
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    @ResponseBody
    private HttpResponse handleSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException e) {
        e.printStackTrace();
        return new HttpResponse(ResponseEnum.DATA_DUPLICATE, null);
    }

    /**
     * 数据超出长度限制
     *
     * @param e 异常实例对象
     * @return http响应结果
     */
    @ExceptionHandler(MysqlDataTruncation.class)
    @ResponseBody
    private HttpResponse handleMysqlDataTruncation(MysqlDataTruncation e) {
        e.printStackTrace();
        return new HttpResponse(ResponseEnum.DATA_TOO_LONG, null);
    }
}
